package cn.chencq.moudle.job.task;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.chencq.moudle.mail.service.MailService;
import cn.chencq.moudle.proxyip.site.PageCrawlerService;
import cn.chencq.moudle.proxyip.site.impl.PageCrawlerServiceImpl;
import cn.chencq.utils.redis.RedisUtils;

@Component("novelUpdateTask")
public class NovelUpdateTask {

	@Autowired
	private PageCrawlerService pageCrawlerService;

	@Autowired
	RedisUtils redis;

	@Autowired
	private MailService mailService;

	private static final String TO_EMAIL = "ccq@chencq.cn";

	private static final String NOVEL_NEW_CHAPTER_NAME = "novel_new_chapter_name";

	public void novelUpdate(String params) {
		String old = redis.get(NOVEL_NEW_CHAPTER_NAME);
		String newChapter = getNewChapterName(params);
		if (StringUtils.isNotBlank(newChapter)) {
			redis.set(NOVEL_NEW_CHAPTER_NAME, newChapter);

			if (StringUtils.isNotBlank(old) && !old.equals(newChapter)) {
				mailService.sendSimpleMail(TO_EMAIL, "小说更小啦!!!", "详情查看" + params);
			}
		}

	}

	public String getNewChapterName(String url) {
		String newChapter = "";

		String html = pageCrawlerService.crawlerHtml(url, null);
		Document document = Jsoup.parse(html);
		Elements els = document.select("div.lb_mulu ul.last9 li a");
		newChapter = els.first().text();

		return newChapter;
	}
}
